# -*- encoding: utf-8 -*-
"""
File Name: compare_cmdb_and_device_configuration
Description:
Author : 'lirui'
date: 2024/3/5
Contact: marjey_lee@163.com
Change Activity:
2024/3/5:
"""
import ll
from projects.monitoring.dedicated_line_monitor.utils.load_cmdb_info import load_dedicated_info_from_cmdb
from projects.monitoring.dedicated_line_monitor.utils.router_config_parse import parse_router_config
from projects.monitoring.dedicated_line_monitor.utils.router_connection import build_router_connection_mapping


class CompareCMDBAndDeviceConfig:
    def __init__(self):
        self.cmdb_info = load_dedicated_info_from_cmdb()
        self.router_connection_mapping = build_router_connection_mapping()
        self.configs = self._load_router_configs()

    def _format_configs(self):
        all_data = {}
        for router_name, items in self.configs.items():
            for item in items:
                item['router_name'] = router_name
                all_data[item['local_address']] = item
        return all_data

    def compare(self):
        router_configs = self._format_configs()
        cmdb_info = self._format_cmdb_info()
        router_keys = list(router_configs.keys())
        cmdb_keys = list(cmdb_info.keys())
        not_in_cmdb = []
        for k in router_keys:
            if k not in cmdb_keys:
                not_in_cmdb.append(router_configs[k])
        redundant_in_cmdb = []
        for k in cmdb_keys:
            if k not in router_keys:
                redundant_in_cmdb.append(cmdb_info[k])
        self.close_connection()
        return not_in_cmdb, redundant_in_cmdb

    def close_connection(self):
        """

        Returns:

        """
        for _, client in self.router_connection_mapping.items():
            try:
                client.close()
            except Exception as e:
                ll.get_logger().error(f'Close ssh connection error: {e}')

    def _format_cmdb_info(self):
        ret_data = {}
        for d in self.cmdb_info:
            local_ip = d['local_mark']
            ret_data[local_ip] = d
        return ret_data

    def _load_router_configs(self):
        """

        Returns:

        """
        config_mapping = {}
        for router_name, client in self.router_connection_mapping.items():
            config = client.send_command('dis cu')
            config = parse_router_config(config)
            config_mapping[router_name] = config
        return config_mapping


def _main():
    compare = CompareCMDBAndDeviceConfig()
    not_in_cmdb, redundant_in_cmdb = compare.compare()


if __name__ == '__main__':
    _main()
